package org.lifeaddict.sybill;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import android.content.Context;
import android.widget.Toast;

public class MUlogin {

	private String user, passwd;
	private String session;
	private boolean logging = true;
	private ArrayList<LvEvent> events;
	private Context context;

	public MUlogin(String user, String passwd) {
		this.user = user;
		this.passwd = passwd;
		this.logIt(user + "/" + passwd);
		this.session = null;
		this.context = null;
	}
	
	public void setContext(Context context) {
		this.context = context;
	}
	
	public void runLogin() {
		this.session = this.login();
	}

	static String getLogin(String cookies, String values) {
		SSLSocket socket = makeSocket();
		String cvalue = "";
		try {
			PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
			sentPostRequest(writer, "wbAnmeldung.durchfuehren", cookies, values);
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			cvalue = getCookie(reader, "PSESSIONID");
			reader.close();
			writer.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cvalue;
	}

	static String getCookie(String target, String cookie, String cookies) {
		SSLSocket socket = makeSocket();
		String cvalue = "";
		try {
			PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
			sendGetRequest(writer, target, cookies);
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			cvalue = getCookie(reader, cookie);
			reader.close();
			writer.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cvalue;
	}

	static void showPage(String target, String cookies) {
		SSLSocket socket = makeSocket();
		try {
			PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
			sendGetRequest(writer, target, cookies);
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			showAll(reader);
			reader.close();
			writer.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static SSLSocket makeSocket() {
		SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
		SSLSocket socket = null;
		try {
			socket = (SSLSocket) factory.createSocket("online.unileoben.ac.at", 443);
			socket.startHandshake();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return socket;
	}

	static void sendGetRequest(PrintWriter writer, String target, String cookies) {
		writer.println("GET /mu_online/" + target + " HTTP/1.1");
		writer.println("Host: online.unileoben.ac.at");
		if (cookies != null) {
			writer.println("Cookie: " + cookies);
		}
		writer.println();
		writer.flush();
		if (writer.checkError())
			System.out.println("SSLSocketClient:  java.io.PrintWriter error");
	}

	static void sentPostRequest(PrintWriter writer, String target, String cookies, String values) {
		writer.println("POST /mu_online/" + target + " HTTP/1.1");
		writer.println("Host: online.unileoben.ac.at");
		writer.println("Content-Length: " + values.length());
		if (cookies != null)
			writer.println("Cookie: " + cookies);
		writer.println();
		if (values != null)
			writer.println(values);
		writer.println();
		writer.flush();
		if (writer.checkError())
			System.out.println("SSLSocketClient:  java.io.PrintWriter error");
	}

	static String getCookie(BufferedReader reader, String cookie) {
		String inputLine = "";
		try {
			while ((inputLine = reader.readLine()) != null)
				if (inputLine.startsWith("Set-Cookie:"))
					break;
		} catch (Exception e) {
			e.printStackTrace();
		}
		inputLine = inputLine.split("Set-Cookie: ")[1];
		String[] cookies = inputLine.split(";");
		String cvalue = "";
		for (int i = 0; i < cookies.length; i++)
			if (cookies[i].startsWith(cookie)) {
				cvalue = cookies[i].split(cookie + "=")[1];
				break;
			}
		return cvalue;
	}

	static void showAll(BufferedReader reader) {
		String inputLine;
		try {
			while ((inputLine = reader.readLine()) != null)
				System.out.println(inputLine);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String login() {
		logIt("Trying to get SessionID for login...");
		String sessionid = getCookie("webnav.ini", "PSESSIONID", null);
		logIt("SessionID is " + sessionid);
		logIt("Trying to get LoginID...");
		String loginid = getCookie("anmeldung.durchfuehren", "PLOGINID", "PSESSIONID=" + sessionid);
		logIt("LoginID is " + loginid);
		logIt("Trying to log in...");
		String logsessionid = getLogin("PSESSIONID=" + sessionid + ";PLOGINID=" + loginid, "cp1=" + this.user + "&cp2=" + this.passwd);
		logIt("Login successful - new SessionID is " + logsessionid);
		logIt("Trying to use logged in session");

		Request reqMenu = new Request(Request.GET, "webnav.menue", logsessionid);
		ArrayList<String> menuData = Parser.readToListSingle(reqMenu.getReader(), "AnmeldeInformation");
		String name = Parser.parseName(menuData);
		String personid = Parser.parsePersonId(menuData);
		String persongrp = Parser.parsePersonGrp(menuData);
		reqMenu.closeRequest();
		logIt("Your Name is " + name);
		logIt("Your PersonID is " + personid);
		logIt("Your PersonGrp is " + persongrp);

		String valPersNr = "?pPersonenId=" + personid + "&pPersonenGruppe=" + persongrp;
		Request reqPersNr = new Request(Request.GET, "visitenkarte.show_vcard" + valPersNr, logsessionid);
		ArrayList<String> vcardData = Parser.readToListSingle(reqPersNr.getReader(), "visitenkarte.student_vcard");
		String personnr = Parser.parsePersonNr(vcardData);
		reqPersNr.closeRequest();
		logIt("Your PersonNr is " + personnr);

		String valLvList = "?cst_person_nr=" + personnr;
		Request reqLvList = new Request(Request.GET, "sa2.lvanmelden" + valLvList, logsessionid);
		ArrayList<String> lvData = Parser.parseLvs(reqLvList.getReader());
		reqPersNr.closeRequest();
		
		Request reqLvs;
		String lvname;
		LvEvent event;
		ArrayList<LvEvent> events = new ArrayList<LvEvent>();
		ArrayList<String> eventData;
		for (String l : lvData) {
			reqLvs = new Request(Request.GET, "wbTvw_List.lehrveranstaltung?pStpSpNr=" + l, logsessionid);
			eventData = Parser.readToListAll(reqLvs.getReader());
			lvname = Parser.parseLvName(eventData);
			event = new LvEvent(lvname);
			Parser.parseLvEvents(eventData, event);
			events.add(event);
			reqLvs.closeRequest();
			// new Toaster(context).execute(lvname);
			logIt(event.toString());
		}
		this.events = events;

		return logsessionid;
	}
	
	public ArrayList<LvEvent> getEvents() {
		return this.events;
	}

	void logIt(String text) {
		if (this.logging)
			System.out.println(text);
	}
}
